package com.longxi.tianjintianbao.ui.presenter.login;

import android.content.Intent;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.greedao.controller.DataUserController;
import com.longxi.tianjintianbao.greedao.entity.User;
import com.longxi.tianjintianbao.listener.SelectUserListener;
import com.longxi.tianjintianbao.ui.adapter.multitype.UserViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.login.IChangeAccountAtView;

import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

public class ChangeAccountAtPresenter extends BasePresenter<IChangeAccountAtView> {

    private MultiTypeAdapter adapter;
    private Items items;

    public ChangeAccountAtPresenter(BaseActivity context) {
        super(context);
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            SelectUserListener listener = new SelectUserListener() {
                @Override
                public void onSuccess(long id) {
                    Intent intent = mContext.getIntent();
                    intent.putExtra("id", id);
                    mContext.setResult(mContext.RESULT_OK, intent);
                    mContext.finish();
                }

                @Override
                public void onTrash(int position) {
                    DataUserController.deleteByUser((User) items.get(position));
                    adapter.notifyItemRemoved(position);
                    items.remove(position);

                    if(items.size() == 0){
                        mContext.showNoData();
                    }
                }
            };
            /* 注册类型和 View 的对应关系 */
            adapter.register(User.class, new UserViewBinder(listener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        String title = intent.getStringExtra(AppConst.TITLE);
        if(title == null){
            title = "切换账号";
        }
        mContext.setTitle(title);
        mContext.setTvLeft("登录");

    }

    public void getUserAccount() {
        items = new Items();
        List<User> userList = DataUserController.selectUserList();
        if(userList.size() > 0){
            items.addAll(userList);
            adapter.setItems(items);
            adapter.notifyDataSetChanged();
            mContext.hideLoading();
        }else{
            mContext.showNoData();
        }
    }

    @Override
    public void detachView() {
        super.detachView();
        this.adapter = null;
        this.items = null;
    }
}
